<!--
 * @Author: 宋绍华
 * @Date: 2024-11-06 17:35:01
 * @LastEditors: 宋绍华
 * @LastEditTime: 2025-01-15 10:59:08
 * @FilePath: \sr_system_manager_ui\src\views\project\mine\index.vue
 * @Description: 项目管理
-->
<template>
	<div class="app-container home">
		<div>
			<SearchBar ref="searchBarRef" v-if="showSearch" :hideRightArea="false" :components="conditionComponents" @search="onSearch" />
			<div class="bg-#f7f8fa h-16px w-140% ml-[-20px] mt-16px"></div>
			<TableForm :right-first-btn-permission="['myProject:export']" :pageSize="20" :auto-height="true" showPagination
				:data="configList" :columns="columns" :tableLoading="loading" :total-count="total"
				v-model:showSearch="showSearch" :showRowSelection="true" btnTitle="发布申报通知" :hideLeftMenu="false"
				:showToolBar="true" :download="(params) => { exportListData(params)}"
				@refresh="refreshTableData"
				@row-dblclick="(rowData) => { console.log('双击行数据》', rowData) }">
				<template #leftMenu="">
					<div>
						<el-button v-hasPermi="['myProject:addPortrait']" @click="linkToCreate(1)" type="primary">新建纵向项目</el-button>
						<el-button v-hasPermi="['myProject:addHorizontal']" @click="linkToCreate(3)" type="primary">新建横向项目</el-button>
						<el-button v-hasPermi="['myProject:addSchool']" @click="linkToCreate(2)" type="primary">新建校级项目</el-button>
					</div>
				</template>
				<template #createTime="{ record }">
					<div v-if="record.approvalTime && record.conclusionTime">
						<span>{{ formateDate(record.approvalTime).format('YYYY-MM-DD') }} ~ {{
						formateDate(record.conclusionTime).format('YYYY-MM-DD') }}</span>
					</div>
					<span v-else>-</span>
				</template>
				<template #projectLevelName="{ record }">
					<div v-if="record.projectNature === projectNatureEnum.projectNatureHorizontal">
						<span>-</span>
					</div>
					<div v-else>
						<span>{{ record.projectLevelName }}</span>	
					</div>
					<span v-else>-</span>
				</template>
				<template #projectNature="{ record }">
					<div>
						<span v-if="record.projectNature === projectNatureEnum.projectNatureHorizontal">横向项目</span>
						<span v-else-if="record.projectNature === projectNatureEnum.projectNatureSchool">校级项目</span>
						<span v-else>纵向项目</span>
					</div>
				</template>
				<template #statusName="{ record }">
          <div class="flex items-center space-x-[8px]">
            <span class="h-[6px] w-[6px] rounded-[3px]"
              :style="{ backgroundColor: intermediateInspectionStatusBgColorMap[record.status as keyof typeof intermediateInspectionStatusBgColorMap] }" />
            <span
              :style="{ color: intermediateInspectionStatusBgColorMap[record.status as keyof typeof intermediateInspectionStatusBgColorMap] }">{{
                record.statusName }}</span>
          </div>
        </template>
				<template #default="{ record }">
					<div class="flex flex-wrap">
						<BtnRender @update="refreshTableData(queryParams)" :record="record" :projectNature="record.projectNature" :status="record.status" />
					</div>
				</template>
			</TableForm>
		</div>

		<ConfirmProject v-model:visible="projectDialogVisible" v-if="projectDialogVisible" />

		<!-- 日志 -->
		<AuditRecordDrawer v-model:visible="auditRecordVisible" v-if="auditRecordVisible" :project-id="curPid" />
	</div>
</template>

<script setup name="Index" lang="ts">
import TableForm from '@/components/TableForm/index'
import SearchBar from '@/components/SearchBar/index'
import ConfirmProject from '../components/ConfirmProject/index.vue'
import { getProjectPageApi, getDicListApi, exportProjectListApi } from '@/api/project'
import formateDate from '@/utils/formateDate'
import { projectNatureEnum } from '@/utils/constEnum'
import AuditRecordDrawer from '@/components/AuditRecordDrawer/index.vue'
import { getDicListById } from '../utils';
import { projectStatusList } from "@/utils/constText";
import BtnRender from '../components/MyProject/BtnRender.vue'
import useUserStore from '@/store/modules/user'
import { intermediateInspectionStatusBgColorMap } from '@/utils/constText';
import { getDepartmentListReq } from "@/api/system/user";
import { DepartmentPageVO } from "@/api/system/user/type";
import { downloadFile } from '@/utils/download'

const projectDialogVisible = ref(false);
const typeList = ref([]) // 项目类别list
const projectTypeList = ref([]) // 项目分类list
const departmentList = ref([]) // 所属院系（部）list
const projectLevelList = ref([]) // 项目级别list
const auditRecordVisible = ref(false)

const route = useRoute()
const curPid = ref('') // 当前项目id
const userStore = useUserStore()
const searchBarRef = ref()
// 导出参数
const downloadParameters = ref({
	projectNature: 9,
  idList: []
})

// 获取学院/部列表
const { run: getDepartmentList } = useRequest(getDepartmentListReq, {
  manual: true,
  onSuccess: (res: DepartmentPageVO[]) => {
    res?.forEach((item) => {
      item.title = item.departmentName
      item.value = item.departmentId
    })
    departmentList.value = res
  }
})

// 获取相关字典
const { run: getDicList } = useRequest(getDicListApi, {
	manual: true,
	onSuccess: (res) => {
		// 类别
		typeList.value = getDicListById(7, res, true)
		// 项目分类
		projectTypeList.value = getDicListById(Number(route.query.projectNature) === projectNatureEnum.projectNatureHorizontal ? 6 : 5, res, true)
		// 项目级别
		projectLevelList.value = getDicListById(18, res, true)
	}
})

// 表头
const columns = ref([
	{
		title: '序号',
		width: 48,
		dataIndex: 'key',
		formatter: (_row: any, _column: any, _cellValue: any, index: number) => {
			return index + 1
		}
	},
	{
		title: '项目（合同）编号',
		dataIndex: 'projectCode',
		slotName: 'projectCode',
		minWidth: 100,
	},
	{
		title: '项目（合同）名称',
		minWidth: 330,
		dataIndex: 'projectName',
		slotName: 'projectName',
	},
	{
		title: '负责人',
		width: 80,
		dataIndex: 'managerName',
		slotName: 'managerName',
		tooltip: true,
	},
	{
		title: '团队成员',
		minWidth: 120,
		dataIndex: 'teamMember',
		slotName: 'teamMember',
		tooltip: true,
	},
	{
		title: '项目分类',
		minWidth: 120,
		dataIndex: 'projectTypeName',
		slotName: 'projectTypeName',
	},
	{
		title: '项目性质',
		minWidth: 80,
		dataIndex: 'projectNature',
		slotName: 'projectNature',
		tooltip: true,
	},
	{
		title: '起止时间',
		minWidth: 170,
		dataIndex: 'createTime',
		slotName: 'createTime',
		tooltip: true,
	},
	{
		title: '项目经费',
		minWidth: 70,
		dataIndex: 'projectFunding',
		slotName: 'projectFunding',
		tooltip: true,
	},
	{
		title: '项目状态',
		width: 110,
		dataIndex: 'statusName',
		slotName: 'statusName',
	},
	{
		title: '操作',
		minWidth: 200,
		dataIndex: 'default',
		slotName: 'default',
	}
])
// 搜索条件组件配置数据
const conditionComponents = ref([
	{
		type: 1,
		key: 'projectType',
		value: '单选框',
		placeholder: '项目分类',
		config: {
			options: projectTypeList
		}
	},
	{
		type: 1,
		key: 'projectNature',
		value: '',
		placeholder: '项目性质',
		config: {
			options: [
				{
					title: '纵向项目',
					value: 1
				},
				{
					title: '校级项目',
					value: 2
				},
				{
					title: '横向项目',
					value: 3
				}
			]
		}
	},
	{
		type: 1,
		key: 'department',
		value: '',
		placeholder: '所属院系（部）',
		config: {
			options: departmentList
		}
	},
	{
		type: 1,
		key: 'projectLevel',
		value: '',
		placeholder: '项目级别',
		config: {
			options: projectLevelList
		}
	},
	{
		type: 2,
		key: 'createTime',
		value: '',
		width: 280,
		placeholder: '起止时间',
		config: {
			pickerOptions: {
				shortcuts: [{
					text: '最近一周',
					onClick(picker) {
						const end = new Date();
						const start = new Date();
						start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
						picker.$emit('pick', [start, end]);
					}
				}, {
					text: '最近一个月',
					onClick(picker) {
						const end = new Date();
						const start = new Date();
						start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
						picker.$emit('pick', [start, end]);
					}
				}, {
					text: '最近三个月',
					onClick(picker) {
						const end = new Date();
						const start = new Date();
						start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
						picker.$emit('pick', [start, end]);
					}
				}]
			}
		}
	},
	{
		type: 1,
		key: 'status',
		value: '单选框',
		placeholder: '项目状态',
		config: {
			options: projectStatusList,
			multiple: true
		}
	},
	{
		type: 0,
		value: '',
		key: 'managerName',
		placeholder: '请输入负责人',
	},
	{
		type: 0,
		value: '',
		key: 'projectName',
		placeholder: '请输入项目名称',
	},
])

const { proxy } = getCurrentInstance();

const configList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);

// 项目列表
const { run: getList } = useRequest(getProjectPageApi, {
	manual: true,
	onSuccess: (response) => {
		configList.value = response.content
		total.value = response.totalElements;
		loading.value = false;
	}
})

const data = reactive({
	form: {},
	queryParams: {
		page: 1,
		size: 20,
		createdBy: userStore.id,
	},
	rules: {
		configName: [{ required: true, message: "参数名称不能为空", trigger: "blur" }],
		configKey: [{ required: true, message: "参数键名不能为空", trigger: "blur" }],
		configValue: [{ required: true, message: "参数键值不能为空", trigger: "blur" }]
	}
});

const { queryParams, form } = toRefs(data);
const router = useRouter();

/* 导出列表数据 */
const { runAsync: exportFile } = useRequest(exportProjectListApi, {
  // false 为自动执行
  manual: true,
  // 请求成功
  onSuccess: () => {
  },
  // 请求失败
  onError: () => {
  },
})
// 导出
const exportListData = async (params) => {
  downloadParameters.value.idList = params
	const res = await exportFile({...downloadParameters.value, ...searchBarRef.value.params, ...queryParams.value})
  downloadFile(res)
}

const refreshTableData = (params) => {
	loading.value = true
	queryParams.value.page = params.page;
	queryParams.value.size = params.size;

	getList({ ...queryParams.value, });
	setTimeout(() => {
		loading.value = false
	}, 1000)
}

const linkToCreate = (type) => {
	router.push({
		path: '/project/mine/create',
		query: {
			projectNature: type
		}
	})
}


/** 表单重置 */
function reset() {
	form.value = {
		config: undefined,
		configName: undefined,
		configKey: undefined,
		configValue: undefined,
		configType: "Y",
		remark: undefined
	};
	proxy.resetForm("configRef");
}

// 搜索
function onSearch(params) {
	const [approvalTime, conclusionTime] = params?.createTime || []
	queryParams.value = Object.assign(queryParams.value, params)
	getList({ ...params, ...queryParams.value, createTime: undefined, approvalTime, conclusionTime })
}

getList({ ...queryParams.value });
getDicList({})
getDepartmentList()
</script>

<style scoped lang="scss">
.home {
	blockquote {
		padding: 10px 20px;
		margin: 0 0 20px;
		font-size: 17.5px;
		border-left: 5px solid #eee;
	}

	hr {
		margin-top: 20px;
		margin-bottom: 20px;
		border: 0;
		border-top: 1px solid #eee;
	}

	.col-item {
		margin-bottom: 20px;
	}

	ul {
		padding: 0;
		margin: 0;
	}

	font-family: "open sans",
	"Helvetica Neue",
	Helvetica,
	Arial,
	sans-serif;
	font-size: 13px;
	color: #676a6c;
	overflow-x: hidden;

	ul {
		list-style-type: none;
	}

	h4 {
		margin-top: 0px;
	}

	h2 {
		margin-top: 10px;
		font-size: 26px;
		font-weight: 100;
	}

	p {
		margin-top: 10px;

		b {
			font-weight: 700;
		}
	}

	.update-log {
		ol {
			display: block;
			list-style-type: decimal;
			margin-block-start: 1em;
			margin-block-end: 1em;
			margin-inline-start: 0;
			margin-inline-end: 0;
			padding-inline-start: 40px;
		}
	}
}
</style>